# models/order.py
from sqlalchemy import Column, Integer, String, Float, Text, Boolean, DateTime
from sqlalchemy.orm import declarative_base
from datetime import datetime
import os

# 数据库配置
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///database.db")

# 创建基类
Base = declarative_base()

class Order(Base):
    __tablename__ = "orders"

    id = Column(Integer, primary_key=True, index=True)
    order_id = Column(String(50), index=True, nullable=False)
    source = Column(String(100), nullable=False)
    domain = Column(String(100), nullable=False)
    # 分开姓和名字段
    customer_first_name = Column(String(100))  # 客户名
    customer_last_name = Column(String(100))   # 客户姓
    customer_name = Column(String(200))        # 完整客户姓名（保持兼容性）
    customer_country = Column(String(100))  # 新增：客户国家
    # 新增客户联系信息字段
    customer_email = Column(String(200))
    customer_phone = Column(String(50))
    customer_address = Column(Text)  # 第一地址
    customer_address_2 = Column(Text)  # 第二地址
    customer_city = Column(String(100))
    customer_state = Column(String(100))
    customer_postcode = Column(String(20))
    
    total = Column(Float)
    currency = Column(String(10), default="USD")
    order_date = Column(DateTime)
    status = Column(String(50), default="processing")
    remote_modified = Column(DateTime)
    created_at = Column(DateTime, default=datetime.utcnow)
    # 新增字段
    item_count = Column(Integer)  # 商品数量
    item_total = Column(Float)    # 商品总价
    shipping_total = Column(Float)  # 运费
    # 新增商品详情字段
    item_details = Column(Text)  # 商品详情（JSON格式存储）

class StatusHistory(Base):
    __tablename__ = "status_history"

    id = Column(Integer, primary_key=True, index=True)
    order_id = Column(String(50), nullable=False)
    source = Column(String(100), nullable=False)
    old_status = Column(String(50))
    new_status = Column(String(50), nullable=False)
    changed_at = Column(DateTime, default=datetime.utcnow)

class SyncLog(Base):
    __tablename__ = "sync_logs"

    id = Column(Integer, primary_key=True, index=True)
    site_name = Column(String(100), nullable=False)
    success = Column(Boolean, nullable=False)
    message = Column(Text)
    synced_at = Column(DateTime, default=datetime.utcnow)